<template>
  <div>
    <el-input v-model="testData.category" placeholder="请输入category"></el-input>
    <el-button @click="testBackend">测试后端</el-button>

    <!-- 添加数据显示区域 -->
    <div v-if="goodsPage">
      <h3>查询结果:</h3>
      <ul>
        <li v-for="good in goodsPage.records" :key="good.id">
          {{ good.name }} - {{ good.price }}
        </li>
      </ul>
      <p>总记录数: {{ goodsPage.total }}</p>
      <p>当前页: {{ goodsPage.current }}</p>
    </div>

    <!-- 添加头像上传测试区域 -->
    <div class="avatar-test">
      <h3>头像上传测试</h3>
      <el-input v-model="avatarTest.uid" placeholder="请输入用户ID"></el-input>
      
      <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :http-request="uploadAvatar"
      >
        <img v-if="avatarTest.imageUrl" :src="avatarTest.imageUrl" class="avatar-preview"/>
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </div>

    <div>
      <el-form class="createOrderForm">
        <el-input label="购买者ID:">
        </el-input>
      </el-form>
    </div>

    <div class="create-order-section">
      <h3>创建订单测试</h3>
      <el-form :model="OrderDataForm.form" label-width="120px">
        <el-form-item label="买家ID">
          <el-input v-model="OrderDataForm.form.buyer_id"></el-input>
        </el-form-item>
        
        <el-form-item label="供应商ID">
          <el-input v-model="OrderDataForm.form.shop_id"></el-input>
        </el-form-item>
        
        <el-form-item label="收货地址">
          <el-input v-model="OrderDataForm.form.address_id"></el-input>
        </el-form-item>
        
        <el-form-item label="订单备注">
          <el-input v-model="OrderDataForm.form.order_message" type="textarea"></el-input>
        </el-form-item>

        <div v-for="(item, index) in OrderDataForm.form.items" :key="index" class="order-item">
          <el-form-item :label="'商品 ' + (index + 1)">
            <el-input v-model="item.gid" placeholder="商品ID" style="width: 120px"></el-input>
            <el-input-number v-model="item.amount" :min="1" placeholder="数量"></el-input-number>
            <el-input v-model="item.unit_price" placeholder="单价" type="number" style="width: 120px"></el-input>
            <el-button type="danger" @click="removeOrderItem(index)" :disabled="OrderDataForm.form.items.length === 1">删除</el-button>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addOrderItem">添加商品</el-button>
          <el-button type="success" @click="submitOrder">提交订单</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="test-addNewAddress">
      <h4>测试新增地址接口</h4>
      <el-form :model="addressForm" label-width="120px">
        <el-form-item label="用户ID">
          <el-input v-model="addressForm.uid" placeholder="用户ID" />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input v-model="addressForm.receiver_name" placeholder="收货人" />
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="addressForm.phoneNumber" placeholder="电话号码"/>
        </el-form-item>
        <el-form-item label="地域">
          <el-input v-model="addressForm.area" placeholder="地域"/>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="addressForm.address" placeholder="详细地址"/>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-radio v-model="addressForm.isDefault" :label="1">是</el-radio>
          <el-radio v-model="addressForm.isDefault" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddress">提交</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div>
      <el-form :model="detailGid">
        <el-input v-model="detailGid.gid"></el-input>
        <el-button type="primary" @click="testDetailedGoods"></el-button>
      </el-form>
    </div>

    <div>
      <el-form :model="testFormData.form">
        <h5>商铺接口部分</h5>
        <el-form-item>
          <el-input v-model="testFormData.form.shopId" placeholder="商铺ID"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.uid" placeholder="用户ID"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.shopName" placeholder="商铺名称"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.province" placeholder="省份"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.city" placeholder="城市"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.area" placeholder="街道"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="testFormData.form.address" placeholder="详细地址"/>
        </el-form-item>
        <el-button type="primary" @click="testShopAPI">提交</el-button>
      </el-form>
    </div>

    <div class="postNewGoods">
      <h3>发布新商品</h3>
      <el-form :model="newGoodsForm" label-width="120px">
        <el-form-item label="商品标题" required>
          <el-input v-model="newGoodsForm.title" placeholder="请输入商品标题"></el-input>
        </el-form-item>
        
        <el-form-item label="商品分类" required>
          <el-cascader
            v-model="newGoodsForm.category"
            :options="categoryOptions"
            :props="{ value: 'value', label: 'label' }"
            placeholder="请选择商品分类"
            @change="handleCategoryChange"
          ></el-cascader>
        </el-form-item>
        
        <el-form-item label="商品价格" required>
          <el-input-number 
            v-model="newGoodsForm.g_price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="库存数量" required>
          <el-input-number 
            v-model="newGoodsForm.stock_quantity" 
            :min="0" 
            :step="1"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="商品标签">
          <el-input 
            v-model="newGoodsForm.tags" 
            placeholder="多个标签用逗号分隔"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="商品描述">
          <el-input 
            v-model="newGoodsForm.describe" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="商品图片" required>
          <el-upload
            class="goods-uploader"
            :show-file-list="true"
            :multiple="true"
            :limit="5"
            :before-upload="beforeGoodsImgUpload"
            :on-exceed="handleExceed"
            :file-list="goodsImagesList"
            :auto-upload="false"
            :on-change="handleGoodsImgChange"
          >
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png格式，单张不超过2MB，最多5张图片
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitNewGoods">发布商品</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button @click="toAlipay">测试支付</el-button>
  </div>
</template>

<script>
import {reactive, ref, onMounted} from "vue";
import http from "@/utils/http.js";
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import httpInstance from "@/utils/http.js";

import router from "@/router/index.js";



const OrderDataForm = reactive({
  form: {
    buyer_id: '',
    shop_id: '',
    address_id: '',
    order_message: '',
    items: [
      {
        gid: '',
        amount: 1,
        unit_price: 0
      }
    ]
  }
})

const testData = reactive({
  category:'',
})

const goodsPage = reactive({
  records: [],
  total: '',
  current: '',
});

const avatarTest = reactive({
  uid: '',
  imageUrl: ''
});

const addressForm = reactive({
  uid: '',
  receiver_name: '',
  phoneNumber: '',
  area: '',
  address: '',
  isDefault: 0
})

const getCategoryTree = async () =>{
  try{
    const response = await http.get('/goods/tree')
    const categoryTree = response.data.data;
  }catch (error){
    console.error(error)
  }
}

const testBackend = async () => {
  http.get(`/goods/pageForCategory/category=${testData.category}`).then(res =>{
      }
  );
};

// 上传前的验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 自定义上传方法
const uploadAvatar = async (options) => {
  if (!avatarTest.uid) {
    ElMessage.error('请先输入用户ID');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', options.file);
    formData.append('uid',avatarTest.uid);
    
    const response = await httpInstance({
      method: 'post',
      url: `/user/avatar/update`,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    });

    console.log(response.code);
    if (response.code === 200) {
      ElMessage.success('头像上传成功');
      avatarTest.imageUrl = URL.createObjectURL(options.file);
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传出错:', error);
    ElMessage.error('上传失败: ' + (error.response?.data?.message || error.message));
  }
};

// 添加一个新的商品项
const addOrderItem = () => {
  OrderDataForm.form.items.push({
    gid: '',
    g_quantity: 1,
    g_price: 0
  })
}

// 删除商品项
const removeOrderItem = (index) => {
  OrderDataForm.form.items.splice(index, 1)
}

// 提交订单
const submitOrder = async () => {
  try {
    const res = await http.post('/order/createOrder', OrderDataForm.form)
    if (res.code === 200) {
      ElMessage.success('订单创建成功')
    } else {
      ElMessage.error(res.msg || '创建失败')
    }
  } catch (error) {
    ElMessage.error('创建订单失败：' + error.message)
  }
}

const submitAddress = async () => {
  try {
    const res = await http.post('/user/address/new', addressForm)
    if (res.code === 200) {
      ElMessage.success('地址添加成功')
      console.log(res)
      Object.assign(addressForm, {
        uid: '',
        receiver_name: '',
        phoneNumber: '',
        area: '',
        address: '',
        isDefault: 0
      })
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加地址失败：' + error.message)
  }
}

const detailGid = reactive({
  gid:'',
})

const testFormData = reactive({
  form: {
    shopId: '',
    uid: '',
    shopName: '',
    province: '',
    city: '',
    area: '',
    address: '',
  }
})

const testShopAPI = async () => {
  try {
    if (!testFormData.form.shopId || !testFormData.form.uid) {
      ElMessage.warning('商铺ID和用户ID不能为空')
      return
    }

    // 打印请求数据，用于调试
    console.log('发送的数据:', testFormData.form)
    
    const res = await http.post('/user/shop/update', testFormData.form)
    console.log('响应数据:', res)
    
    if (res.code === 200) {
      ElMessage.success('店铺信息更新成功')
      testFormData.form = {
        shopId: '',
        shopName: '',
        province: '',
        city: '',
        area: '',
        address: '',
      }
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('完整错误信息:', error)
    ElMessage.error('更新店铺信息失败：' + error.message)
  }
}

const testDetailedGoods = async () =>{
  try {
    const res = await http.get(`/goods/${detailGid.gid}/detail`,detailGid.gid)
    console.log(res)
    if(res === 200){

    }
      }catch (error){
        ElMessage.error('查询失败'+error.message)
      }
}

// 新增商品表单数据
const newGoodsForm = reactive({
  title: '',
  category: '',
  g_price: 0,
  stock_quantity: 0,
  tags: '',
  describe: '',
  shop_id: '1', // 这个可能需要从用户登录信息中获取
  province: '',
  city: '',
});

const goodsImagesList = ref([]);
const categoryOptions = ref([]);

// 图片上传前的验证
const beforeGoodsImgUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('商品图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('商品图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 处理超出最大上传数量
const handleExceed = () => {
  ElMessage.warning('最多只能上传5张图片');
};

// 处理图片改变
const handleGoodsImgChange = (file, fileList) => {
  goodsImagesList.value = fileList;
};

// 处理分类改变
const handleCategoryChange = (value) => {
  newGoodsForm.category = value[value.length - 1];
};

// 获取分类树
const loadCategoryTree = async () => {
  try {
    const res = await http.get('/goods/tree');
    if (res.code === 200) {
      categoryOptions.value = res.data;
    }
  } catch (error) {
    ElMessage.error('获取商品分类失败');
  }
};

// 提交新商品
const submitNewGoods = async () => {
  try {
    if (!newGoodsForm.title || !newGoodsForm.category || !goodsImagesList.value.length) {
      ElMessage.warning('请填写必要信息并上传至少一张商品图片');
      return;
    }

    const formData = new FormData();
    // 将商品信息转换为JSON字符串
    formData.append('good', JSON.stringify(newGoodsForm));
    
    // 添加商品图片
    goodsImagesList.value.forEach(file => {
      formData.append('goodsImages', file.raw);
    });

    const res = await http.post('/goods/newGoods', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (res.code === 200) {
      ElMessage.success('商品发布成功');
      resetForm();
    } else {
      ElMessage.error(res.msg || '发布失败');
    }
  } catch (error) {
    ElMessage.error('发布商品失败：' + error.message);
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(newGoodsForm, {
    title: '',
    category: '',
    g_price: 0,
    stock_quantity: 0,
    tags: '',
    describe: '',
    province: '',
    city: '',
  });
  goodsImagesList.value = [];
};

export default {
  components: { Plus },
  setup() {
    // 页面加载时获取分类树
    onMounted(() => {
      loadCategoryTree();
    });

    return {
      testData,
      testBackend,
      goodsPage,
      avatarTest,
      beforeAvatarUpload,
      uploadAvatar,
      OrderDataForm,
      addOrderItem,
      removeOrderItem,
      submitOrder,
      addressForm,
      submitAddress,
      detailGid,
      testDetailedGoods,
      testFormData,
      testShopAPI,
      getCategoryTree,
      newGoodsForm,
      goodsImagesList,
      categoryOptions,
      beforeGoodsImgUpload,
      handleExceed,
      handleGoodsImgChange,
      handleCategoryChange,
      submitNewGoods,
      resetForm,
      toAlipay,
    };
  },
};
</script>

<style lang="less" scoped>
.avatar-test {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #eee;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  margin-top: 10px;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .avatar-preview {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.create-order-section {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #eee;
}

.order-item {
  padding: 10px;
  margin: 10px 0;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.postNewGoods {
  margin: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;

  .goods-uploader {
    .el-upload {
      margin-right: 10px;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
  }
}
</style>
